/**
 * @name 百度编辑器表单类
 * @author Yangxing
 * @date 2018-07-13
 */
var EditorForm= function () {

    var errors={
        'up':{
            success:false,
            message:"没有收上级"
        },
        'down':{
            success:false,
            message:"没有下级"
        },
        'radiosValue':{
            success:false,
            message:"请填写选择内容"
        },
        'radiosBaseValues':{
            success:false,
            message:"请选择默认值"
        },
        'inputValue':{
            success:false,
            message:"默认值不能为空"
        },
        'weight':{
            success:false,
            message:"宽度不能为空"
        },
        'height':{
            success:false,
            message:"高度不能为空"
        },
        'configuration':{
            success:false,
            message:"是否验证不能为空"
        },
        'selectName':{
            success:false,
            message:"下拉框的值不能为空"
        },
        'noSelect':{
            success:false,
            message:"请选择下拉框"
        },
        'selectExist':{
            success:false,
            message:"内容已经存在"
        }
    };

    var radiosHtml= function (methods) {
        var html='<tr><td><div class="radio i-checks"><label>';
        html+='<input type="'+methods+'" name="radion"></label></div></td>';
        html+='<td><input type="text" class="form-control inputValue"></td>';
        html+= '<td><a href="javascript:;" class="btn btn-xs btn-primary">';
        html+='<i class="fa fa-arrow-circle-up"></i></a>';
        html+='<a href="javascript:;" class="btn btn-xs btn-primary" style="margin-left: 5px">';
        html+='<i class="fa fa-arrow-circle-down"></i></a>';
        html+='<a href="javascript:;" class="btn btn-xs btn-primary" style="margin-left: 5px">';
        html+='<i class="fa fa-times-circle"></i></a></td></tr>';
        console.log(html);
        return html;
    }

    var deleteHandler= function () {
        $('table').on('click','a.btn',function () {
            console.log('this is radios');
            if (!$(this).children().hasClass('fa-times-circle')){
                return;
            }
            var ths= $(this);
            parent.layer.confirm("您确定要删除？",{
                btn:['确定','删除'],
                shade:0.8
            },function (index) {
                parent.layer.close(index);
                ths.closest('tr').remove();
            })
        })
    }
    
    var selects=[];

    /**
     * 所有表单的通用函数
     *
     * @param method
     */
    var initHandler= function (method) {
        var oNode = null, thePlugins = method;
        window.onload = function () {
            if (UE.plugins[thePlugins].editdom) {
                oNode = UE.plugins[thePlugins].editdom;
            }
        }
        dialog.onok= function () {
            $('form').validate({
                rules:{
                    name:"required"
                },
                messages:{
                    name:"必填"
                },
                submitHandler:function (form) {
                    if (method=='radios'){
                        if(!radiosValidateHandler('radio')){
                            return;
                        }
                    }
                    if (method=='checkboxs' && !radiosValidateHandler('checkbox')){
                        return;
                    }
                    
                    if ((method=='text' || method=='textarea') && !validateTextHandler()){
                        return;
                    }
                    if (method=='select' && !validateSelectHandler()){
                        return;
                    }
                    var params={};
                    if(method=='radios'){
                        params = radiosParams('radio');
                    }else if(method=="checkboxs"){
                        params= radiosParams('checkbox');
                    }else if(method=='text' || method=="textarea"){
                        params= textHandler();
                    }else if (method=='select'){
                        params= selectParams();
                    }
                    params= JSON.stringify(params);
                    $.ajax({
                        type:'post',
                        url:'../form/submit',
                        data:{'params':params},
                        dataType:'json',
                        success:function (data) {
                            if (data.success){
                                data= data.data;
                                if (method=='radios'){
                                    radiosSuccessHandler(data,'radio');
                                }else if (method=='text'){
                                    textSuccessHandler(data);
                                }else if (method=='textarea'){
                                    textareaSuccessHandle(data);
                                }else if (method=='checkboxs'){
                                    radiosSuccessHandler(data,'checkbox');
                                }else if (method=='select'){
                                    selectSuccessHandler(data);
                                }
                                return;
                            } 
                            Common.alert(data)
                        }
                    })
                }
            });
            $('form').submit();
            return false;
        }
    };
    
    var textareaSuccessHandle= function (data) {
        var html='<textarea name="'+data.inputName+'" title="' + data.name;
        html+= '" style="width: '+data.width+'px; height:'+data.height+'px;"';
        html+='tplid="'+data.typeId+'" tpltype="'+data.inputType+'" fromid="'+data.id;
        html+='" leipiplugins="textarea" value="'+data.inputValue+'">'+data.inputValue+'</textarea>';
        editor.execCommand("insertHtml",html,true);
        dialog.close(false);
    }
    
    var radiosSuccessHandler= function (data,method) {
        var html = '<span leipiplugins="radios" tplid="'+data.typeId
            +'" typeid="'+data.typeId+'" fromid="'+data.id
            +'" title="'+data.inputName+'" name="leipiNewField">';
        html +=getOptions(data,method);
        html +='</span>';
        editor.execCommand('insertHtml',html,true);
        dialog.close(false);
    };
    
    var selectSuccessHandler= function (data) {
        var oNode=null;
        oNode = createElement('select','leipiNewField');
        oNode.setAttribute('title',data.name);
        oNode.setAttribute('name',data.inputName);
        oNode.setAttribute('tplid',data.typeId);
        oNode.setAttribute('tpltype',data.inputType);
        oNode.setAttribute('leipiPlugins','select');
        oNode.setAttribute('fromid',data.id);
        if(data.width!='' && data.height!=''){
            oNode.setAttribute('style','width:'+data.width+'px;height:'
                +data.height+'px;line-height:'+data.height+'px;font-size:14px;');
        }
        // Add all available options.
        for ( var i = 0 ; i < data.options.length ; i++ ) {
            var sText    = data.options[i] ;
            if ( sText.length == 0 ) {
                sText = sText ;
            }
            var oOption = fnAddComboOption( oNode, sText, sText ) ;
            if ( sText == data.inputValue ) {
                fnSetAttribute( oOption, 'selected', 'selected' ) ;
                oOption.selected = true ;
            }
        }
        //firefox要利用span
        editor.execCommand('insertHtml',oNode.outerHTML,true);
        dialog.close(false);
    };

    var fnSetAttribute= function( element, attName, attValue ) {
        if ( attValue == null || attValue.length == 0 ){
            element.removeAttribute( attName, 0 ) ;
        } else {
            element.setAttribute( attName, attValue, 0 ) ;
        }
    }

    var fnAddComboOption= function( combo, optionText, optionValue, documentObject, index ) {
        var oOption ;
        if ( documentObject ) {
            oOption = documentObject.createElement("option") ;
        } else {
            oOption = document.createElement("option") ;
        }
        if ( index != null ) {
            combo.options.add( oOption, index ) ;
        } else {
            combo.options.add( oOption ) ;
        }
        oOption.innerHTML = optionText.length > 0 ? fnHTMLEncode( optionText ) : '&nbsp;' ;
        oOption.value     = optionValue ;
        return oOption ;
    }


    var fnHTMLEncode= function( text ) {
        if ( !text ) {
            return '' ;
        }
        text = text.replace( /&/g, '&amp;' ) ;
        text = text.replace( /</g, '&lt;' ) ;
        text = text.replace( />/g, '&gt;' ) ;
        return text ;
    }
    var getOptions= function (data,method) {
        var options= data.options;
        var html='';
        if (options!=null && options.length>0){
            for(var i=0; i<options.length; i++) {
                html += '<input name="' + data.inputName + '"';
                    if (data.inputValue== options[i]){
                        html+=" checked='checked' ";
                    }
                html+= '" value="' + options[i] + '" type="'+method+'"/>'+options[i];
            }
        }
        return html;
    }
    
    var textSuccessHandler= function (data) {
        //添加控件执行块
        oNode = createElement('input','leipiNewField');
        oNode.setAttribute('type','text');
        oNode.setAttribute('title',data.name);
        oNode.setAttribute('value',data.inputValue);
        oNode.setAttribute('name',data.inputName);
        oNode.setAttribute('tplid',data.typeId);
        oNode.setAttribute('tpltype',data.inputType);
        oNode.setAttribute('leipiPlugins','text');
        oNode.setAttribute('fromid',data.id);
        if(data.width!='' && data.height!=''){
            oNode.setAttribute('style','width:'+data.width+'px;height:'+data.height+'px;');
        }
        editor.execCommand('insertHtml',oNode.outerHTML,true);
        dialog.close(false);
    }

    var radioHandler= function () {
      $('.ibox').on("click",'a.add',function () {
          $('tbody').append(radiosHtml('radio'));
          Common.checkbox();
      });
      deleteHandler();
      moveHandler('up');
      moveHandler('down');
    };

    var checkboxHandler= function () {
        $('.ibox').on("click",'a.add',function () {
            $('tbody').append(radiosHtml('checkbox'));
            Common.checkbox();
        });
        deleteHandler();
        moveHandler('up');
        moveHandler('down');
    }

    var moveHandler=function(method){
        $('table').on("click",'a.btn',function () {
            if (!$(this).children().hasClass('fa-arrow-circle-'+method)){
                return;
            }
            if(method=='up'){
                var length= $(this).closest('tr').prevAll().length;
                if (length==0){
                    Common.alert(errors.up);
                    return;
                }
                $(this).closest('tr').prev().before($(this).closest('tr'));
            }else {
                var length= $(this).closest('tr').nextAll().length;
                if (length==0){
                    Common.alert(errors.down);
                    return;
                }
                $(this).closest('tr').next().after($(this).closest('tr'));
            }
        })
    };

    var radiosValidateHandler=function (method) {
        var values=$('.inputValue');
        if (values.length==0){
            Common.alert(errors.radiosValue);
            return false;
        }
        var base=$('input[type='+method+']:checked');
        if (base.length==0){
            Common.alert(errors.radiosBaseValues);
            return false;
        }
        return true;
    };


    var radiosParams=function (method) {
        var params={};
        var options=[];
        $('.inputValue').each(function () {
            options.push($(this).val());
        })
        params.name=$('#name').val();
        params.inputValue = $('input[type='+method+']:checked').closest('tr').find('.inputValue').val();
        params.dbType = 1;
        params.typeId = typeId;
        params.fileType = type;
        params.options= options;
        params.inputValueNum = '542';
        params.w = '220';
        params.h = '35';
        params.magnificent = '4';
        return params;
    };

    var createElement= function(type, name) {
        var element = null;
        try {
            element = document.createElement('<' + type + ' name="' + name + '">');
        } catch (e) {
        }
        if (element == null) {
            element = document.createElement(type);
            element.name = name;
        }
        return element;
    };

    var textHandler= function () {
        var params= {};
        params.name= $("#name").val();
        params.inputValue= $('#value').val();
        params.w=$("#width").val();
        params.h=$("#height").val();
        params.confirmation=$('input[name=confirmation]:checked').val();
        params.typeId=typeId;
        params.fileType= type;
        params.magnificent="hjr";
        return params;
    };

    var selectHandler= function () {
      $('.ibox').on("click",'button.department',function () {
          var value= $('#positionName').val();
          if (value==null || value==""){
              Common.alert(errors.selectName);
              return;
          }
          if (selects.hasCode(value)){
              Common.alert(errors.selectExist);
              return;
          } 
          selects.push(value);
          $('#positionName').val("");
          var html='<option value="'+value+'">';
          html+=value+'</option>';
          $('select').append(html);
      });
        moveSelectHandler('up');
        moveSelectHandler('down');
        delectSelectHandler();
    };

    var delectSelectHandler= function () {
        $('.ibox').on("click",'a.btn',function () {
            if (!$(this).children().hasClass('fa-times-circle')){
                return;
            }
            var select=$('select option:selected');
            if (select==0){
                Common.alert(errors.noSelect);
                return;
            }
            select.remove();
        })
    };
    
    var selectParams= function () {
        var params={};
        params.name= $("#name").val();
        params.options= selects;
        params.inputValue= $('select option:selected').val();
        params.w= $('#width').val();
        params.h= $('#height').val();
        params.typeId=typeId;
        params.fileType= type;
        params.magnificent="hjr";
        return params;
    }

    var moveSelectHandler= function (method) {
        $('.ibox').on("click",'a.btn',function () {
            if (!$(this).children().hasClass('fa-arrow-circle-'+method)){
                return;
            }
            if(method=='up'){
                var length= $('select option:selected').prevAll().length;
                console.log($('select option:selected')[0]);
                if (length==0){
                    Common.alert(errors.up);
                    return;
                }
                $('select option:selected').prev().before($('select option:selected'));
            }else {
                var length= $(this).closest('tr').nextAll().length;
                if (length==0){
                    Common.alert(errors.down);
                    return;
                }
                $('select option:selected').next().after($('select option:selected'));
            }
        })
    }

    var validateSelectHandler= function () {
        var width= $('#width').val();
        if (width==null || width==""){
            Common.alert(errors.weight);
            return false;
        }
        var height= $('#height').val();
        if (height==null || height==""){
            Common.alert(errors.height);
            return false;
        }
        var options= $('select option');
        if (options.length==0){
            Common.alert(errors.radiosValue);
            return false;
        }
        var optionBase=$('select option:selected');
        if (optionBase.length==0){
            Common.alert(errors.radiosBaseValues);
            return false;
        }
        return true;
    };

    var validateTextHandler= function () {
        var inputValue= $('#value').val();
        if (inputValue==null || inputValue==''){
            Common.alert(errors.inputValue);
            return false;
        } 
        var weight=$('#width').val();
        if (weight==null || weight==''){
            Common.alert(errors.weight);
            return false;
        } 
        var height= $("#height").val();
        if (height==null || height==''){
            Common.alert(errors.height);
            return false;
        } 
        var configuration= $('input[name= configuration]:checked');
        if (configuration.length==0){
            Common.alert(errors.configuration);
            return false;
        } 
        return true;
    };
    
    return {
        radio:function () {
            initHandler("radios");
            radioHandler();
        },

        text:function () {
            Common.input();
            initHandler('text');
        },

        textarea:function () {
            Common.input();
            initHandler('textarea');
        },
        checkbox:function () {
            checkboxHandler();
            initHandler("checkboxs");
        },
        select:function () {
            Common.init();
            selectHandler();
            initHandler('select');
        }
    }
}();